package com.muqi.server.service;

import com.muqi.server.common.utilis.StudentSimilarityRecommender;
import com.muqi.server.domain.bo.CollaborativeFilteringBO;
import com.muqi.server.domain.po.CollaborativeFilteringPO;
import com.muqi.server.mapper.CollaborativeFilteringMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.math3.linear.RealMatrix;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CollaborativeFilteringService {

    private final CollaborativeFilteringMapper collaborativeFiltering;
    public List<CollaborativeFilteringBO> getCollaborativeFiltering(String name) {
        //获得目标学生数据
        List<CollaborativeFilteringBO> targetStudent = collaborativeFiltering.getStudentsByName(name);
        //全部学生
        List<CollaborativeFilteringBO> allStudents = collaborativeFiltering.selectList(null).stream()
                .map(this::convertCollaborativeFilteringBOToBo).toList();
        //相似度
        StudentSimilarityRecommender recommender = new StudentSimilarityRecommender();
        //获取推荐列表
        List<CollaborativeFilteringBO> recommendations = recommender.recommendForSpecifiedStudents(targetStudent, allStudents, 3);
        //存储targetStudent内
        List<String> recommendationNames = new ArrayList<>();
        recommendations.forEach(student -> recommendationNames.add(student.getName()));

        targetStudent.forEach(student -> student.setRecommendation(recommendationNames));
        System.out.println("targetStudent"+targetStudent);
        return targetStudent;
    }

    public List<CollaborativeFilteringBO> getCollaborativeFiltering() {
        List<CollaborativeFilteringBO> list = collaborativeFiltering.selectList(null).stream()
                .map(this::convertCollaborativeFilteringBOToBo).toList();

        StudentSimilarityRecommender recommender = new StudentSimilarityRecommender();
        RealMatrix similarityMatrix = recommender.calculateStudentSimilarity(list);

        // 为每个学生生成推荐
        recommender.recommendSimilarStudents(list, similarityMatrix, 3);
        System.out.println(list);
        // 打印推荐结果
        return list;
    }



    private CollaborativeFilteringBO convertCollaborativeFilteringBOToBo(CollaborativeFilteringPO collaborativeFilteringPO) {
        CollaborativeFilteringBO collaborativeFilteringBO = new CollaborativeFilteringBO();
        collaborativeFilteringBO.setSemester(collaborativeFilteringPO.getSemester());
        collaborativeFilteringBO.setName(collaborativeFilteringPO.getName());
        collaborativeFilteringBO.setGpa(collaborativeFilteringPO.getGpa());
        return collaborativeFilteringBO;
    }
}
